package com.cjc.config.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cjc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * satoken 拦截器
 * @Author: 陈江灿
 * @CreateTime: 2025-01-20
 */
@Slf4j
@Component
public class SaTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("sa-token");
        if(!StrUtil.isEmpty(token)){
//            Object id_Obj = StpUtil.getLoginIdByToken(token);
//            Long id = Long.valueOf(id_Obj.toString());
//            if(id != null){
//                return true;
//            }
            return true;
        }
        response.setContentType("application/json;charset=UTF-8");
        String result = JSONUtil.toJsonStr(R.fail(403, "未登录！"));
        response.getWriter().println(result);
        response.getWriter().flush();
        return false;
    }
}
